use reqwest::{redirect::Policy, *};
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;
use std::result::Result::Ok;

#[derive(Deserialize)]
struct ApiResponse {
    id: u32,
    name: String,
}

pub async fn test() {
    // let blocking_client = reqwest::blocking::Client::new();
    let client = Client::new();

    // let proxy = Proxy::http("http://proxy.example:8080").unwrap();
    // let cli = Client::builder()
    //     .proxy(proxy)
    //     .timeout(Duration::from_secs(10))
    //     .redirect(Policy::limited(5))
    //     .build().unwrap();

    // JSON post请求
    // let data = json!({"key": "value"});
    // let resp = client.post("http://example.com").json(&data).send().await.unwrap();

    // 表单 post请求
    // let params = [("name", "John"), ("age", "30")];
    // let resp2 = client.post("http://example.com").form(&params).send().await.unwrap();

    let resp3 = client.get("https://www.baidu.com/").send().await;
    match resp3 {
        Ok(res) => {
            if res.status().is_success() {
                // 处理成功响应
                let body = res.text().await;               
                if let Ok(content) = body {
                    println!("响应内容: {}", content);
                } else {
                    eprintln!("response parsing error: {}", body.err().unwrap());
                }
                // 处理 JSON 响应
                // let api_response: ApiResponse = res.json::<ApiResponse>().await?;
                // println!("ID: {}, Name: {}", api_response.id, api_response.name);

            } else {
                eprintln!("请求失败: {}", res.status());
            }
        }
        Err(e) => eprintln!("req sent error: {e}"),
    }
}

#[tokio::main]
pub async fn req_main() {
    test().await;
}
